<template>
  <el-card shadow="never">
    <el-card class="mb20" shadow="never">
      <div slot="header">
        <span>基本信息</span>
      </div>
      <first-form @notSubmit="handleNotSubmit" @sendData="handleSendData" ref="firstForm" />
      <span slot="extra">
        <el-button @click="handleCancel">返回</el-button>
      </span>
    </el-card>
    <el-card class="mb20" shadow="never">
      <div slot="header" style="overflow: hidden;line-height:32px">
        <span>资产图片</span>
        <!-- <el-button class="fr" size="small" type="primary" @click="handleUpload">上传</el-button> -->
        <el-upload
          class="upload-demo fr"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="handleChange"
          :http-request="httpRequest"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </div>
      <template v-if="fileList.length">
        <el-row :gutter="24">
          <el-col :span="8" v-for="(item,index) in fileList" :key="index">
            <el-image v-viewer :src="item.url" fit="cover" />
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <empty-comp ref="emptyComp" />
      </template>
    </el-card>
    <div class="tl-center">
      <el-button size="large" class="w120 mr20" @click="handleCancel">取消</el-button>
      <el-button
        size="large"
        :disabled="this.type === 'detail'"
        class="w120 mr20"
        type="primary"
        @click="e => handleSure(e)"
      >{{ this.type === 'add' ? '新增' : '修改' }}</el-button>
      <el-tooltip class="item" effect="light" content="保留上部输入内容，清空图片，可继续新增" placement="top">
        <el-button
          :loading="addLoad"
          class="w120"
          @click="e => handleSure(e, true)"
          type="primary"
          v-show="this.type === 'add'"
          size="large"
        >继续新增</el-button>
      </el-tooltip>
    </div>
  </el-card>
</template>

<script>
import FirstForm from './FirstForm'
import { getSession, setSession, openNotification, removeSession } from '@/utils/util'
import { insertAssetsInfo, updateAssetsInfo, manageUpdate } from '@/api/assets'
import { infoCreate, infoUpdate } from '@/api/assetsNew'
import { saveOnlyUploads } from '@/api/assets'

export default {
  components: {
    FirstForm
  },
  data() {
    return {
      addLoad: false,
      detailObj: this.$route.params.obj || getSession('assetsRecord'),
      type: this.$route.params.type || getSession('assetsType'),
      listData: [],
      firstFormData: {},
      imageWrapData: '',
      firstTrue: true,
      url: '',
      fileList: []
    }
  },
  mounted() {
    const { obj, type } = this.$route.params
    if (JSON.stringify(this.$route.params) !== '{}') {
      this.url = this.$route.params.url
      const { type } = this.$route.params
      setSession('assetsRecord', this.$route.params.obj)
      setSession('assetsType', this.$route.params.type)
      this.$refs.firstForm.edit(type, this.detailObj)
    }
    if (this.type === 'detail') {
      this.$message.info('详情只支持查看，不能修改')
    }
    if (this.type !== 'add') {
      console.log('detailObj', this.detailObj)
      const { pictureUrl } = this.detailObj
      if (pictureUrl && pictureUrl.length > 0) {
        this.fileList = [...pictureUrl]
      }
    }
  },
  methods: {
    handleNotSubmit(bool, num) {
      if (num === 1) {
        this.firstTrue = bool
      }
    },
    // 拿到子组件数据
    handleSendData(obj, num) {
      if (num === 1) {
        this.firstFormData = Object.assign({}, obj)
        this.firstTrue = true
      } else {
        this.imageWrapData = obj
      }
    },
    handleCancel() {
      this.$router.push({
        name: 'assetsCheck'
      })
    },
    async handleSure(e, copy = false) {
      this.addLoad = false
      await this.$refs.firstForm.getFormData()
      if (this.firstTrue) {
        if (JSON.stringify(this.firstFormData) !== '{}') {
          let arr = []
          this.fileList.map(v => {
            arr.push(v.uploadId)
          })
          let param = { ...this.firstFormData, photoList: arr.join(',') }
          let res = ''
          let mes = ''
          if (this.type === 'add') {
            res = await infoCreate(param)
            mes = '新增操作成功'
            if (res.state === '000000') {
              console.log('copy', copy)
              if (copy) {
                openNotification('success', '新增操作成功，可继续新增')
                // this.$refs.imageWrap.clear()
                this.fileList = []
                return false
              } else {
                this.$router.push({
                  name: 'assetsCheck'
                })
              }
            }
          } else if (this.type === 'edit') {
            res = await infoUpdate(param)
            // if (this.url === 'assetsManage') {
            //   // 固定资产管理调用另外一个修改
            //   res = await manageUpdate(param)
            // } else {
            //   res = await updateAssetsInfo(param)
            // }
            mes = '修改操作成功'
          }
          if (res.state === '000000') {
            this.addLoad = false
            openNotification('success', mes)
            this.$router.push({
              name: 'assetsCheck'
            })
          }
        }
      } else {
        openNotification('error', '请填写必填内容')
      }
    },
    handleChange(file, fileList) {
      console.log('handleChange', file, fileList)
    },
    async httpRequest(file, fileList) {
      console.log('httpRequest', file, fileList)

      const formData = new FormData()
      formData.append('file', file.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        console.log('res', res)
        if (res.data) {
          const { data } = res
          this.fileList.push(data)
          this.fileList[this.fileList.length - 1].uploadId = data.uploadId
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].status = 'done'
          console.log('fileList', this.fileList)
        }
      })
    }
  },
  destroyed() {
    removeSession('assetsRecord')
    removeSession('assetsType')
  }
}
</script>

<style scoped>
.w120 {
  width: 120px;
}

.el-card.mb20 {
  overflow: inherit;
}
.upload-demo >>> .el-upload-list {
  display: none;
}
</style>
<style>
.vue-treeselect--disabled .vue-treeselect__control {
  background: #ffffff;
  color: rgba(0, 0, 0, 0.65);
  cursor: default;
}
</style>